import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Checkbox, Toast } from 'antd-mobile'
import http from '../../api'
import style from './index.module.css'

export default function Login() {
  const [checked, setChecked] = useState(false)
  // 输入的手机号是否正确
  const [isTrue, setIsTrue] = useState(false)
  // 输入的手机号
  const [phone, setPhone] = useState('')
  const navigate = useNavigate()

  function changePhone(e: any) {
    const re = /^1[3-9]\d{9}$/
    setIsTrue(() => re.test(e.target.value))
    setPhone(e.target.value)
  }

  function getCode() {
    if (phone === '') {
      Toast.show({
        content: '请输入手机号',
        position: 'top'
      })
      return
    }
    if (!isTrue) {
      Toast.show({
        content: '请检查手机号是否正确',
        position: 'top'
      })
      return
    }
    if (!checked) {
      Toast.show({
        content: '请勾选用户协议',
        position: 'top'
      })
      return
    }
    sendCode()
    // 路由跳转
    navigate('/sendcode', { state: { phone } })
  }
  async function sendCode() {
    http('post', '/mty/noteRandomCode/getLoginCode', { tel: phone })
  }

  return (
    <div className={style['login-container']}>
      <div className={style.mask}>
        <div className={style['title-content']}>
          <div>牧童游</div>
          <div>城市周边乡村游</div>
        </div>
        {/* 电话号码输入和获取验证码 */}
        <div className={style['phone-container']}>
          <div className={style['phone']}>
            <div className={style['un-phone']}>
              <span>+86</span>
              <img src="/static/arrow/icon-arrow-down-fff.png" alt="" />
            </div>
            <input type="number" placeholder="请输入手机号" value={phone} onInput={(e) => changePhone(e)} />
          </div>
          <div className={`${style['get-code']} ${checked && isTrue && style.active}`} onClick={getCode}>
            获取验证码
          </div>
        </div>
        {/* 用户协议 */}
        <div className={style.robots}>
          <div className={style['text']}>
            <Checkbox
              checked={checked}
              onChange={(value) => {
                setChecked(value)
              }}
            ></Checkbox>
            <div>阅读并同意牧童游《用户协议》和《隐私政策》</div>
          </div>
          <div>未注册的手机号验证后将自动创建牧童账号</div>
        </div>
      </div>
    </div>
  )
}
